package com.gress.shop.service.impl;

import com.google.common.collect.Lists;
import com.gress.shop.bo.*;
import com.gress.shop.bo.example.MemberRoleRelationExample;
import com.gress.shop.dao.IActionDao;
import com.gress.shop.dao.IMemberRoleRelationDao;
import com.gress.shop.dao.IRoleActionRelationDao;
import com.gress.shop.dao.IRoleDao;
import com.gress.shop.service.IRoleService;
import com.gress.shop.service.inner.IMemberInternalService;
import com.gress.shop.util.HappyException;
import com.gress.shop.util.ShiroUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.print.attribute.HashAttributeSet;
import java.util.List;

/**
 * Created xiongwen with 2018/4/12 10:39
 * Description:
 */
@Service
public class RoleService implements IRoleService {

    @Resource
    private IActionDao actionDao;
    @Resource
    private IMemberRoleRelationDao memberRoleRelationDao;
    @Resource
    private IRoleActionRelationDao roleActionRelationDao;
    @Resource
    private IRoleDao roleDao;
    @Resource
    private IMemberInternalService memberInternalService;

    @Override
    public Role queryByMemberId(String memberId) {
        String roleId = getRoleIdByMemberId(memberId);
        return roleDao.selectByPrimaryKey(roleId);
    }

    private String getRoleIdByMemberId(String memberId) {
        MemberRoleRelation relation = memberRoleRelationDao.selectByMemberId(memberId);
        if (null==relation) return null;
        return relation.getRoleId();
    }


    @Override
    public Role queryByEmail(String email) {
        String memberId = memberInternalService.getMemberIdByEmail(email);
        return queryByMemberId(memberId);
    }

    @Override
    public void saveRole(Role role) {
        String email = ShiroUtil.getEmail();
        role.setCreateBy(email);
         roleDao.insertSelective(role);
    }

    @Override
    public void updateMemberRole(String email, String roleId) {
        if (roleDao.selectByPrimaryKey(roleId) == null) {
            throw new HappyException("角色已经失效");
        }
        memberInternalService.queryByEmail(email);
        if (null == memberInternalService.queryByEmail(email)) {
            throw new HappyException("用户未注册");
        }
        String currentEmail = getCurrentEmail();
        MemberRoleRelation memberRoleRelation = memberRoleRelationDao.selectByMemberId(email);
        if (null == memberRoleRelation) {
            memberRoleRelation = new MemberRoleRelation();
            memberRoleRelation.setRoleId(roleId);
            memberRoleRelation.setMemberId(email);
            memberRoleRelation.setCreateBy(currentEmail);
            memberRoleRelationDao.insertSelective(memberRoleRelation);
        }else {
            memberRoleRelation.setRoleId(roleId);
            memberRoleRelationDao.updateByPrimaryKeySelective(memberRoleRelation);
        }
    }

    @Override
    public void saveMemberRole(MemberRoleRelation relation) {
        String createBy = ShiroUtil.getEmail();
        String memberId = relation.getMemberId();
        String roleId = relation.getRoleId();
        if (!roleDao.checkIsExist(roleId)){
            //角色不存在呀
            throw new HappyException("角色跑到火星了,请重新添加");
        }
        MemberRoleRelationExample example = new MemberRoleRelationExample();
        example.createCriteria().andMemberIdEqualTo(memberId);
        List<MemberRoleRelation> memberRoleRelations = memberRoleRelationDao.selectByExample(example);
        if (CollectionUtils.isEmpty(memberRoleRelations)) {
            //新增操作
            memberRoleRelationDao.insert(relation);
        }else {
            MemberRoleRelation oldRelation = memberRoleRelations.get(0);
            oldRelation.setRoleId(roleId);
            oldRelation.setCreateBy(createBy);
            try {
                //乐观锁更新
                memberRoleRelationDao.updateByPrimaryKey(oldRelation);
            } catch (Exception e) {
                e.printStackTrace();
                throw new HappyException("请不要重复操作");
            }
//            if (oldRelation.getIsValid() == 1) {
//                //已经存在角色，告警
//
//            }else {
//                //已经被移除了角色
//            }
        }
    }


    @Override
    @Transactional
    public void deleteRoleById(String roleId) {
        //清除用户关联
        List<MemberRoleRelation> memberRoleRelations = memberRoleRelationDao.selectByRoleId(roleId);
        memberRoleRelations.forEach(e -> memberRoleRelationDao.deleteByPrimaryKey(e.getId()));
        //清除权限关联
        List<RoleActionRelation> roleActionRelations = roleActionRelationDao.selectByRoleId(roleId);
        roleActionRelations.forEach(e -> roleActionRelationDao.deleteByPrimaryKey(e.getId()));
        //清除角色
        roleDao.deleteByPrimaryKey(roleId);
    }

    @Override
    public List<Role> queryAllRoles() {
        List<Role> roles = roleDao.selectAll();
        if (CollectionUtils.isEmpty(roles)) {
            roles = Lists.newArrayList();
        }
        return roles;
    }

    @Override
    public List<MemberRoleRelation> queryMemberRoles() {
        List<MemberRoleRelation> memberRoleRelations = memberRoleRelationDao.selectAll();
        if (CollectionUtils.isEmpty(memberRoleRelations)) {
            memberRoleRelations = Lists.newArrayList();
        }
        return memberRoleRelations;
    }

    @Override
    public List<RoleActionRelation> queryActionRoles() {
        List<RoleActionRelation> memberActionRelations = roleActionRelationDao.selectAll();
        if (CollectionUtils.isEmpty(memberActionRelations)) {
            memberActionRelations = Lists.newArrayList();
        }
        return memberActionRelations;
    }

    @Override
    @Transactional
    public void addRole(Role role, List<String> strings) {
        if (role==null) throw new HappyException("系统异常");
        String roleCode = role.getRoleCode();
        if (StringUtils.isEmpty(role.getName())||StringUtils.isEmpty(roleCode)) throw new HappyException("param is empty");
        Role codeRole = roleDao.queryByCode(roleCode);
        if (null!=codeRole) throw new HappyException("权限编码已经存");
        String email = getCurrentEmail();
        role.setCreateBy(email);
        String roleId = roleDao.insertSelective(role);

        strings.forEach(e->{
            RoleActionRelation ra = new RoleActionRelation();
            ra.setActionId(e);
            ra.setRoleId(roleId);
            ra.setCreateBy(email);
            roleActionRelationDao.insertSelective(ra);
        });
    }

    private String getCurrentEmail() {
        String email = ShiroUtil.getUser().getEmail();
        if (StringUtils.isEmpty(email)) throw new HappyException("获取当前用户失败");
        return email;
    }

    @Override
    public Role queryByRoleId(String roleId) {
        Role role = roleDao.selectByPrimaryKey(roleId);
        return role;
    }

    @Override
    public List<RoleActionRelation> queryRelationByRoleId(String roleId) {
        List<RoleActionRelation> roleActionRelations = roleActionRelationDao.selectByRoleId(roleId);
        if (CollectionUtils.isEmpty(roleActionRelations)) {
            return Lists.newArrayList();
        }
        return roleActionRelations;
    }

    @Override
    @Transactional
    public void deleteRoleAction(List<String> idList) {
        idList.forEach(e->{
            roleActionRelationDao.deleteByPrimaryKey(e);
        });
    }

    @Override
    @Transactional
    public void updateRoleAction(List<String> actionId, Role role) {
        String roleId = role.getId();
        if (null==roleDao.selectByPrimaryKey(roleId)) throw new HappyException("更新的角色已经失效");
        roleDao.updateByPrimaryKeySelective(role);
        String email = getCurrentEmail();
        actionId.forEach(e->{
            RoleActionRelation ra = new RoleActionRelation();
            ra.setActionId(e);
            ra.setCreateBy(email);
            ra.setRoleId(roleId);
            roleActionRelationDao.insertSelective(ra);
        });
    }
}

